<?php

namespace App\Models;


use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Admin extends Authenticatable implements JWTSubject
{
    use  Notifiable;
    use SoftDeletes;
    protected $table = 'admin';
    protected $fillable = [
        'username', 'password', 'user_id', 'role_id'
    ];
    protected $hidden = ['password'];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     *查询用户
     * @param $query
     * @param $name
     */
    public function scopeName($query, $name)
    {
        if ($name) {
            $query->where('username', 'like', '%' . $name);
        }

    }

    /**
     * 添加后台管理员
     * @param $data
     * @return bool
     */
    static public function add($data)
    {

        $re = self::create($data);
        if ($re) {

            return true;
        }
        return false;
    }

    /**
     * 编辑
     * @param $id
     * @param $data
     * @return bool
     */
    static public function edit($id, $data)
    {
        $admin = self::find($id);

        $admin->username = $data['username'];
        if (!empty($data['password'])) {
            $admin->password = bcrypt($data['password']);
        }
        if (!empty($data['user_id'])) {
            $admin->user_id = $data['user_id'];
        }

        $admin->role_id = $data['role_id'];
        if ($admin->save()) {
            return true;
        }
        return  false;

    }
}
